package com.fita.wechat.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fita.entity.coupon.Coupon;
import com.fita.wechat.service.CouponService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.handler.CookieHandler;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.core.wechat.entity.cfg.JsConfig;
import com.fita.entity.data.Country;
import com.fita.entity.data.Location;
import com.fita.entity.data.Supplier;
import com.fita.entity.order.Order;
import com.fita.entity.set.Set;
import com.fita.wechat.Constant;
import com.fita.wechat.processor.WechatProcessor;
import com.fita.wechat.service.DataService;
import com.fita.wechat.service.OrderService;
import com.fita.wechat.service.SetService;
import com.fita.wechat.web.interceptor.Wechat;

import java.util.List;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/shopping")
public class WebShoppingController {
    
    private static final Logger logger = LoggerFactory.getLogger(ShoppingController.class);
    
    private static final String USER_AGENT = "User-Agent";
    
    private static final String MICRO_MESSENGER = "MicroMessenger";

    @Autowired
    private CouponService couponService;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Location> locationService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Supplier> supplierService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Country> countryService;
    
    @Autowired
    private SetService setService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private WechatProcessor wechatProcessor;
    
    /**
     * 获取结果页
     * 
     * @param login
     * @param type
     * @param orderId
     * @param sign
     * @param mobile
     * @param request
     * @return
     */
    @Wechat
    @RequestMapping(value = "/web-result", method = RequestMethod.GET)
    public ModelAndView result(@RequestParam("type") String type,
                               @RequestParam("orderId") Long orderId,
                               @RequestParam("sign") String sign,
                               @RequestParam("mobile") String mobile,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        
        try {
            
            ModelAndView modelAndView = new ModelAndView();
            
            Order order = orderService.load(orderId, sign, mobile);
            
            if(order == null) {
                logger.info("get current order null");
                modelAndView.setViewName("shopping/orders-info-error");
                return modelAndView;
            }
            
            logger.info("get current order [{}]", order.getId());
            
            modelAndView.addObject("order", order);
            cookieHandler.addCookie(response, Constant.MOBILE_KEY, mobile, 31*24*60*60);
            
            Location pickupLocation = locationService.load(Location.class, "code", order.getPickupLocation());
            Location returnLocation = locationService.load(Location.class, "code", order.getReturnLocation());
            modelAndView.addObject("pickupLocation", pickupLocation);
            modelAndView.addObject("returnLocation", returnLocation);
            
            Supplier supplier = supplierService.load(Supplier.class, "code", order.getBrand());
            modelAndView.addObject("supplier", supplier);
            
            Country country = countryService.load(Country.class, "code", order.getCountry());
            modelAndView.addObject("country", country);
            
            Set set = setService.load(order.getDetails().getSetMeal());
            modelAndView.addObject("set", set);
            
            int days = DateUtils.daysBetween(order.getPickupDate(), order.getReturnDate());
            modelAndView.addObject("days", days);

            if (StringUtils.equalsIgnoreCase(type, "staying")) {
                modelAndView.setViewName("shopping/staying-orders-info-result");
            } else {
                
                modelAndView.setViewName("shopping/orders-info-result");
                
                //是否微信环境
                boolean isMicroMessenger = this.isMicroMessenger(request);
                if(isMicroMessenger) {
                    String curl = WebUtils.getRealRequestURL(request);
                    JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
                    modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
                }
                modelAndView.addObject("isMicroMessenger", isMicroMessenger);

                //展示所有可使用，包括被占用的优惠券
                List<Coupon> coupons = couponService.listAllAvailableCoupons(order.getAgent().getId(),order.getCnyPayPrice());
                logger.info("orderRetailAmount [{}] couponSize [{}]",order.getRetailAmount(),coupons.size());
                modelAndView.addObject("coupons",JsonUtils.toJson(coupons));
            }

            if(order.getUserCouponId() != null){

                Coupon userCoupon = couponService.load(order.getUserCouponId());
                modelAndView.addObject("userCoupon",userCoupon);
                
                boolean needpay = (order.getCnyPayPrice().intValue() - (userCoupon.getAmount()/100) > 0) ? true : false;
                modelAndView.addObject("needpay", needpay);
            } else {
                modelAndView.addObject("needpay", true);
            }
            
            // ，获取已有用户信息（optional）
            return modelAndView;
            
        } catch (Exception e) {
            logger.info("get web shooping error", e);
            ModelAndView modelAndView = new ModelAndView("shopping/orders-info-error");
            return modelAndView;
        }
    }
    
    /**
     * 
     * @param request
     * @return
     */
    private boolean isMicroMessenger(HttpServletRequest request) {
        
        String userAgent = request.getHeader(USER_AGENT);
        logger.info("#isMicroMessenger() - Get user agent [{}].", userAgent);
        
        return org.apache.commons.lang3.StringUtils.isNoneBlank(userAgent) && userAgent.indexOf(MICRO_MESSENGER) >= 0;
    }
}
